package xgenerator.ui.swing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.metal.MetalComboBoxUI;

//自定义ComboBox显示效果
public class FileComboBoxUI extends MetalComboBoxUI {
	private JComboBox component;

	public static ComponentUI createUI(JComboBox c) {
		return new FileComboBoxUI(c);
	}

	public FileComboBoxUI(JComboBox c) {
		component = c;
	}

	static final StringBuffer HIDE_POPUP_KEY = new StringBuffer("HidePopupKey");

	@Override
	public void configureArrowButton() {
		if (arrowButton != null) {
			arrowButton.setEnabled(comboBox.isEnabled());
			arrowButton.setFocusable(comboBox.isFocusable());
			arrowButton.setRequestFocusEnabled(false);

			// 替换原下拉按钮鼠标事件
			// arrowButton.addMouseListener( popup.getMouseListener() );
			// arrowButton.addMouseMotionListener( popup.getMouseMotionListener() );
			arrowButton.addActionListener(new ActionListener() {

				// 修改事件为选择目录
				public void actionPerformed(final ActionEvent e) {
					JFileChooser chooser = new JFileChooser();
					chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

					// chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
					// chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG Image Files", "jpg"));

					int returnVal = chooser.showOpenDialog(null);
					if (returnVal == JFileChooser.APPROVE_OPTION) {

						component.removeAllItems();
						component.addItem(chooser.getSelectedFile().getAbsolutePath());
					}
				}
			});

			arrowButton.resetKeyboardActions();
			arrowButton.putClientProperty("doNotCancelPopup", HIDE_POPUP_KEY);
			arrowButton.setInheritsPopupMenu(true);
		}
	}
}